; util.asm
; Utility routines

	.export bdiv
	.export bmul
	.export wdiv
	.export bcd2bin

	.segment "ZEROPAGE"
	
op2:		.res 1
	
	.segment "CODE"

;
;	Byte division
;	INPUT:
;		A .... operand 1
;		X .... operand 2
;	OUTPUT:
;		X := A / X
;

bdiv:		stx op2
			sec
			ldx #$FF
@lpdiv:		inx
			sbc op2
			bcs @lpdiv
			rts

;	Word/byte division
;	INPUT:
;		AX .. operand 1 (<= 7FFF)
;		Y .... operand 2
;	OUTPUT:
;		Y := AX / Y

wdiv:		sty op2
			sec
			ldy #$FF
@lpwdiv:	iny
			sbc op2
			bcs @lpwdiv
			sec
			dex
			bpl @lpwdiv
			rts
			
;
;	Byte multiplication
;	INPUT:
;		A .... operand 1
;		X .... operand 2
;	OUTPUT:
;		A/X .... A*X
;

bmul:		cpx #2
			bcs @domul
			dex
			bne @retzero
			rts
@retzero:	lda #0
			tax
			rts
@domul:		stx op2
			ldy op2
			dey
			sta op2
			ldx #0
@lpmul:		clc
			adc op2
			bcc @nocry
			inx
@nocry:		dey
			bne @lpmul
			rts

;
;	Convert a BCD to a binary number
;	INPUT:
;		A ... 2-digit BCD number
;	OUTPUT:
;		A ... binary number
;	NOTE:
;		X,Y .. unchanged
;

bcd2bin:	pha
			and #$0F
			sta op2
			pla
			and #$F0
			lsr
			pha
			adc op2
			sta op2
			pla
			lsr
			lsr
			adc op2
			rts		
